# encoding:utf-8
# 遍历字典
# encoding:utf-8
import random
import sys
from django.shortcuts import HttpResponse
import json
import redis
from IR.Util.Variables import Constant
from IR.Util.DB import DB
from  IR.moduels.snippet import Snippet
from  IR.moduels.Indexing import Search
import jieba
import re
import math
import heapq
from pymongo import MongoClient
import Util

def pretty_echo_dict(obj, indent=' '):
    def _pretty(obj, indent):
        for i, tup in enumerate(obj.items()):
            k, v = tup
            # 如果是字符串则拼上""
            if isinstance(k, basestring): k = '"%s"' % k
            if isinstance(v, basestring): v = '"%s"' % v
            # 如果是字典则递归
            if isinstance(v, dict):
                v = ''.join(_pretty(v, indent + ' ' * len(str(k) + ': {')))  # 计算下一层的indent
            # case,根据(k,v)对在哪个位置确定拼接什么
            if i == 0:  # 开头,拼左花括号
                if len(obj) == 1:
                    yield '{%s: %s}' % (k, v)
                else:
                    yield '{%s: %s,\n' % (k, v)
            elif i == len(obj) - 1:  # 结尾,拼右花括号
                yield '%s%s: %s}' % (indent, k, v)
            else:  # 中间
                yield '%s%s: %s,\n' % (indent, k, v)

    print ''.join(_pretty(obj, indent))

def save_index_to_redis():

    index_path = u"C:/InformationRetrieval/IR_Final/IR/moduels/Indexing/IndexData/"
    r_server = redis.Redis(host="localhost", port=6379)
    # try:
    with open(index_path+u"InvertedIndex.json", 'r') as f:
        InvertedIndex =f.read()
        print (InvertedIndex)
        r_server.set('InvertedIndex', InvertedIndex)
    with open(index_path+u"word_df.json", 'r') as f:
        word_df = f.read()
        print (word_df)
        r_server.set('word_df', word_df)
    with open(index_path+u"permutermIndex.json", 'r') as f:
        permIndex = f.read()
        print (permIndex)
        r_server.set('permIndex', permIndex)
    with open(index_path+u"documentVectors.json", 'r') as f:
        documentVectors = f.read()
        print (documentVectors)
        r_server.set('documentVectors', documentVectors)
    with open(index_path+u"documentLengths.json", 'r') as f:
        documentLengths = f.read()
        print (documentLengths)

        r_server.set('documentLengths', documentLengths)
    with open(index_path+u"stop_words.txt", 'r') as f:
        stop_words=f.read()
        print (stop_words)
        r_server.set('stop_words', stop_words)
        # gbk_stop_words = f.readlines()
        # stop_words = [x.strip().decode('gbk') for x in gbk_stop_words]
    r_server.set('has_data',"yes")
    return True
    # except Exception, e:
    #      print (e.message)
    #      return False
def get_index_from_redis(key):
    r_server = redis.Redis(host="localhost", port=6379)
    return r_server.get(key)

def sort_news(news_list,mode=0):
    if(mode==0 or news_list==None or len(news_list)<=0 ):
        return news_list
    else:
        res=news_list
        if(mode==1):
            res = sorted(news_list, key=lambda e: e.get('time'), reverse=True)
        else:
            res=sorted(news_list, key=lambda e: e.get('conment_num'), reverse=True)
        return res